//
//  SceneDelegate.swift
//  DragonWallet
//
//  Created by volantPig on 2023/12/26.
//

import UIKit
import SwiftyJSON

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        
        if UserDefaults.standard.bool(forKey: "hadShowAdvert") == false {
            // 创建第一个视图控制器
            let advertViewController = JDAdvertLaunchViewController()
            advertViewController.currentWindow = window
            advertViewController.view.backgroundColor = UIColor.commonColor()
            self.window?.rootViewController = advertViewController
        }

        // 显示window
        self.window?.makeKeyAndVisible()
        
        for userActivity in connectionOptions.userActivities {
            OpenInstallSDK.continue(userActivity)
        }
        
        guard let _ = (scene as? UIWindowScene) else { return }
    }
    
    func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
        WXApi.handleOpenUniversalLink(userActivity, delegate: self)
        OpenInstallSDK.continue(userActivity)
    }
    

    
    
    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }

    
    
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        if #available(iOS 16.0, *) {
            if URLContexts.first?.url.host() == "safepay" {
                if let url = URLContexts.first?.url {
                    self.alipayCallback(url)
                }
            }
        } else {
            // Fallback on earlier versions
            if URLContexts.first?.url.host == "safepay" {
                if let url = URLContexts.first?.url {
                    self.alipayCallback(url)
                }
            }
        }
        
        guard let url = URLContexts.first?.url else { return }
        WXApi.handleOpen(url, delegate: self) // 确保self实现了WXApiDelegate
        
    }
    
    func alipayCallback(_ url: URL) {
        
        AlipaySDK.defaultService().processAuth_V2Result(url) { responseDic in
            print("认证的返回结果:\(responseDic),可能没有结果，但是，不调这个方法，那边不做返回")
        }
        
        AlipaySDK.defaultService()?.processOrder(withPaymentResult: url, standbyCallback: { (resultDic) in
//                [AnyHashable : Any]
            
            print("看一下这个内容:\(resultDic)")
            
            let orderState = JSON(resultDic as Any)["resultStatus"].intValue
            switch orderState {
            case 8000:
                print("支付正在处理中")
            case 4000:
                print("支付失败")
                NotificationCenter.default.post(name: NSNotification.Name("payResult"), object: "失败")
            case 6001:
                print("支付取消")
                NotificationCenter.default.post(name: NSNotification.Name("payResult"), object: "取消")
            case 6002:
                print("网络错误")
            case 9000:
                print("支付成功")
                NotificationCenter.default.post(name: NSNotification.Name("payResult"), object: "成功")
            default:
                break
            }
        })
    }
    

}

extension SceneDelegate: WXApiDelegate {
    func onReq(_ req: BaseReq) {

        print("微信参数:\(req)")
    }
    
    func onResp(_ resp: BaseResp) {
        print("微信回调:\(resp))")
        // 微信授权
        if resp.isKind(of: SendAuthResp.self) {
            
            let authResp = resp as? SendAuthResp
            
            switch authResp?.errCode {
            case WXSuccess.rawValue:
                // 授权成功
//                NSString *code = authResp.code;
//               NSLog(@"微信授权成功，code: %@", code);
//               
//               // 使用code向你的服务器请求access_token和用户信息
//               [self getWeChatAccessTokenWithCode:code];

                let code = authResp?.code
                // 这个是个什么code:Optional("091bT42w3U8B653VSZZv3ufJqK2bT42S")，是openId吗？，绑定用这个吗？
//                print("这个是个什么code:\(code)，是openId吗？，绑定用这个吗？")
                
//                @property (nonatomic, copy, nullable) NSString *state;
//                @property (nonatomic, copy, nullable) NSString *lang;
//                @property (nonatomic, copy, nullable) NSString *country;
                
//                print("这个是个什么state:\(authResp?.state)")
//                print("这个是个什么lang:\(authResp?.lang)")
//                print("这个是个什么country:\(authResp?.country)")
//                
//                这个是个什么state:Optional("xiaolongbao")
//                这个是个什么lang:nil
//                这个是个什么country:nil
                
                NotificationCenter.default.post(name: NSNotification.Name.init("bindWechatResult"), object: nil, userInfo: ["wechatKey": code ?? ""])
                
            case WXErrCodeUserCancel.rawValue:
                // 用户点击取消并返回
                print("用户取消提示")
            case WXErrCodeAuthDeny.rawValue:
                // 授权失败
                print("授权失败提示")
            case WXErrCodeUnsupport.rawValue:
                // 微信不支持
                print("微信不支持提示")
            default:
                break
            }
        }
        
        // 微信支付
        // 官方示例返回值
        if resp.isKind(of: PayResp.self) {
            
            let payResp = resp as? PayResp
            
            switch payResp?.errCode {
            case WXSuccess.rawValue:
                // 支付成功
                let result = payResp?.returnKey
                print("支付完成后，拿到了:\(result)")
                NotificationCenter.default.post(name: NSNotification.Name("payResult"), object: "成功")
            case WXErrCodeUserCancel.rawValue:
                // 用户点击取消并返回
                print("用户取消提示")
                NotificationCenter.default.post(name: NSNotification.Name("payResult"), object: "取消")
            case WXErrCodeAuthDeny.rawValue:
                // 支付失败
                print("支付失败提示")
                NotificationCenter.default.post(name: NSNotification.Name("payResult"), object: "失败")
            case WXErrCodeUnsupport.rawValue:
                // 微信不支持
                print("微信不支持提示")
            default:
                break
            }
        }
        
    }
}
